export interface ChatMessage {
  id: string
  content: string
  role: 'user' | 'assistant'
  timestamp: Date
  isStreaming?: boolean
}

interface ChatRequest {
  message: string
  history?: Omit<ChatMessage, 'id' | 'timestamp' | 'isStreaming'>[]
  conversation_id?: string
}

interface StreamWithMemoryRequest {
  message: string
  conversation_id?: string
  user_id?: string
}

interface ConversationHistory {
  id: number
  conversation_id: number
  role: string
  content: string
  sequence_number: number
  created_at: string
}

interface ConversationSummary {
  id: number
  conversation_id: number
  summary_content: string
  start_message_seq: number
  end_message_seq: number
  summary_type: string
  created_at: string
}

interface ChatResponse {
  content: string
  conversation_id: string
  message_id: string
}

export class ChatService {
  private static instance: ChatService
  private baseUrl: string = '/api/v1'

  private constructor() {}

  static getInstance(): ChatService {
    if (!ChatService.instance) {
      ChatService.instance = new ChatService()
    }
    return ChatService.instance
  }

  async sendMessage(message: string, history?: Omit<ChatMessage, 'id' | 'timestamp' | 'isStreaming'>[]): Promise<AsyncIterable<string>> {
    const request: ChatRequest = {
      message,
      history
    }

    try {
      const response = await fetch(`${this.baseUrl}/chat/stream`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(request),
      })

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }

      if (!response.body) {
        throw new Error('Response body is null')
      }

      const reader = response.body.getReader()
      const decoder = new TextDecoder()

      return {
        async *[Symbol.asyncIterator]() {
          try {
            let buffer = ''
            while (true) {
              const { done, value } = await reader.read()
              if (done) break
              
              const chunk = decoder.decode(value, { stream: true })
              buffer += chunk
              
              // 处理Server-Sent Events格式: data: {content}\n\n
              const lines = buffer.split('\n\n')
              buffer = lines.pop() || '' // 保留最后一个不完整的行
              
              for (const line of lines) {
                if (line.startsWith('data: ')) {
                  const content = line.slice(6) // 移除 'data: ' 前缀
                  if (content.trim()) {
                    yield content
                  }
                }
              }
            }
          } finally {
            reader.releaseLock()
          }
        }
      }
    } catch (error) {
      console.error('Error sending message:', error)
      throw error
    }
  }

  async sendNonStreamingMessage(message: string, conversationId?: string): Promise<ChatResponse> {
    const request: ChatRequest = {
      message,
      conversation_id: conversationId
    }

    try {
      const response = await fetch(`${this.baseUrl}/chat`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(request),
      })

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }

      return await response.json()
    } catch (error) {
      console.error('Error sending message:', error)
      throw error
    }
  }

  async getConversationHistory(conversationId: string): Promise<ChatMessage[]> {
    try {
      const response = await fetch(`${this.baseUrl}/chat/conversation/${conversationId}/history`)
      
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }

      const data = await response.json()
      return data.messages.map((msg: any) => ({
        id: msg.id,
        content: msg.content,
        role: msg.role,
        timestamp: new Date(msg.timestamp)
      }))
    } catch (error) {
      console.error('Error fetching conversation history:', error)
      throw error
    }
  }

  // 带记忆功能的流式聊天
  async sendMessageWithMemory(message: string, conversationId?: string, userId?: string): Promise<{ stream: AsyncIterable<string>, conversationId: string }> {
    const request: StreamWithMemoryRequest = {
      message,
      conversation_id: conversationId,
      user_id: userId
    }

    try {
      const response = await fetch(`${this.baseUrl}/chat/stream-with-memory`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(request),
      })

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }

      if (!response.body) {
        throw new Error('Response body is null')
      }

      // 从响应头获取conversation_id
      const responseConversationId = response.headers.get('X-Conversation-ID') || conversationId || 'unknown'

      const reader = response.body.getReader()
      const decoder = new TextDecoder()

      let extractedConversationId = responseConversationId

      const stream = {
        async *[Symbol.asyncIterator]() {
          try {
            let buffer = ''
            while (true) {
              const { done, value } = await reader.read()
              if (done) break
              
              const chunk = decoder.decode(value, { stream: true })
              buffer += chunk
              
              // 处理Server-Sent Events格式: data: {content}\n\n
              const lines = buffer.split('\n\n')
              buffer = lines.pop() || '' // 保留最后一个不完整的行
              
              for (const line of lines) {
                if (line.startsWith('data: ')) {
                  const content = line.slice(6) // 移除 'data: ' 前缀
                  if (content.trim()) {
                    // 检查是否是结束标记
                    if (content === '[DONE]') {
                      break
                    }
                    
                    // 检查是否包含conversation_id信息
                    if (content.includes('"conversation_id"')) {
                      try {
                        const data = JSON.parse(content)
                        if (data.conversation_id) {
                          extractedConversationId = data.conversation_id.toString()
                          // 跳过包含conversation_id的内容，不输出给用户
                          continue
                        }
                      } catch (e) {
                        // 如果解析失败，尝试正则匹配
                        const match = content.match(/"conversation_id":\s*(\d+)/)
                        if (match) {
                          extractedConversationId = match[1]
                          continue
                        }
                      }
                    }
                    
                    // 直接输出内容，不尝试解析JSON
                    yield content
                  }
                }
              }
            }
          } finally {
            reader.releaseLock()
          }
        }
      }

      return { stream, conversationId: extractedConversationId }
    } catch (error) {
      console.error('Error sending message with memory:', error)
      throw error
    }
  }

  // 智能体模式发送消息（流式）
  async sendAgentMessage(message: string, conversationId?: string, userId?: string): Promise<{ stream: AsyncIterable<string>, conversationId: string }> {
    const request: StreamWithMemoryRequest = {
      message,
      conversation_id: conversationId,
      user_id: userId
    }

    try {
      const response = await fetch(`${this.baseUrl}/chat/agent/stream`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(request),
      })

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }

      if (!response.body) {
        throw new Error('Response body is null')
      }

      // 从响应头获取conversation_id
      const responseConversationId = response.headers.get('X-Conversation-ID') || conversationId || 'unknown'

      const reader = response.body.getReader()
      const decoder = new TextDecoder()

      let extractedConversationId = responseConversationId

      const stream = {
        async *[Symbol.asyncIterator]() {
          try {
            let buffer = ''
            while (true) {
              const { done, value } = await reader.read()
              if (done) break
              
              const chunk = decoder.decode(value, { stream: true })
              buffer += chunk
              
              // 处理Server-Sent Events格式: data: {content}\n\n
              const lines = buffer.split('\n\n')
              buffer = lines.pop() || '' // 保留最后一个不完整的行
              
              for (const line of lines) {
                if (line.startsWith('data: ')) {
                  const content = line.slice(6) // 移除 'data: ' 前缀
                  if (content.trim()) {
                    // 检查是否包含conversation_id信息
                    if (content.includes('"conversation_id"')) {
                      try {
                        const match = content.match(/"conversation_id":\s*(\d+)/)
                        if (match) {
                          extractedConversationId = match[1]
                          // 跳过包含conversation_id的内容，不输出给用户
                          continue
                        }
                      } catch (e) {
                        // 如果解析失败，继续处理
                      }
                    }
                    yield content
                  }
                }
              }
            }
          } finally {
            reader.releaseLock()
          }
        }
      }

      return { stream, conversationId: extractedConversationId }
    } catch (error) {
      console.error('Error sending agent message:', error)
      throw error
    }
  }

  // 获取对话历史消息
  async getConversationHistoryFromDB(conversationId: number): Promise<ConversationHistory[]> {
    try {
      const response = await fetch(`${this.baseUrl}/chat/conversation/${conversationId}/history`)
      
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }

      const data = await response.json()
      return data.messages || []
    } catch (error) {
      console.error('Error fetching conversation history from DB:', error)
      throw error
    }
  }

  // 获取对话摘要
  async getConversationSummaries(conversationId: number): Promise<ConversationSummary[]> {
    try {
      const response = await fetch(`${this.baseUrl}/chat/conversation/${conversationId}/summaries`)
      
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }

      const data = await response.json()
      return data.summaries || []
    } catch (error) {
      console.error('Error fetching conversation summaries:', error)
      throw error
    }
  }

  // 获取用户的对话列表
  async getUserConversations(userId: number): Promise<any[]> {
    try {
      const response = await fetch(`${this.baseUrl}/chat/conversations/user/${userId}`)
      
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }

      const data = await response.json()
      return data.conversations || []
    } catch (error) {
      console.error('Error fetching user conversations:', error)
      throw error
    }
  }
}